package org.ns.tomdog.server.support;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class RequestInputStream extends InputStream {

    private ByteArrayInputStream cache;
    private InputStream socketInputStream;
    private int length;
    public RequestInputStream(byte[] cacheBytes, InputStream socketInputStream) {
        this.cache = new ByteArrayInputStream(cacheBytes);
        this.socketInputStream = socketInputStream;
        this.length = cacheBytes.length;
    }


    @Override
    public int read() throws IOException {
        byte[] b = new byte[1];
        int res = read(b);
        if (res == -1) {
            return -1;
        }
        return b[0];
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (length == 0) {
            return socketInputStream.read(b, off, len);
        }
        if (length >= len) {
            length = length - len;
            return cache.read(b, off, len);
        }
        cache.read(b, off, length);
        len = len - length;
        int res = socketInputStream.read(b, off, len);
        if (res <= 0) {
            res = length;
        } else {
            res += length;
        }
        length = 0;
        return res;
    }

    @Override
    public int read(byte[] b) throws IOException {
        return read(b, 0, b.length);
    }
}
